<!-- 节目管理 -->
<template>
	<div class="app-container">
		<el-row :gutter="20">
			<!--分组数据-->
			<el-col :span="4" :xs="24">
				<div>
					<el-button type="primary" size="mini" @click="handleQueryAll">
						全部展示
					</el-button>
				</div>
				<div class="head-container" style="margin-top:5px">
					<el-input
						v-model="name"
						:placeholder="$t('equipment.groupingInput')"
						clearable
						size="small"
						prefix-icon="el-icon-search"
						style="margin-bottom: 20px"
					/>
				</div>
				<div class="head-container tree">
					<el-tree
						ref="tree"
						:data="groupOptions"
						:props="defaultProps"
						:expand-on-click-node="false"
						:filter-node-method="filterNode"
						:highlight-current="true"
						default-expand-all
						@node-click="handleNodeClick"
					>
						<div
							slot-scope="{ node, data }"
							class="el-tree-node__label custom-tree-node custom-tree-item"
							style="position: relative;"
						>
							<span class="name">{{ data.name }}</span>
							<div
								class="right-btns"
								style="position: absolute;right: 0; top: 0; background: #F5F7FA; height: 100%"
								@click.stop
							>
								<svg-icon
									v-hasPerm="['group_add']"
									icon-class="plus"
									@click="addGroup(node, data)"
								/>
								<svg-icon
									v-hasPerm="['group_edit']"
									icon-class="edit"
									@click="editGroup(node, data)"
								/>
								<svg-icon
									v-if="data.parentId > 0"
									v-hasPerm="['group_del']"
									icon-class="delete"
									@click="deleteGroup(node, data)"
								/>
							</div>
						</div>
					</el-tree>
				</div>
			</el-col>

			<!--节目数据-->
			<el-col :span="20" :xs="24">
				<el-form
					v-show="showSearch"
					ref="queryForm"
					:model="queryParams"
					:inline="true"
					label-width="68px"
				>
					<el-form-item :label="$t('equipment.programName')" prop="name">
						<el-input
							v-model="queryParams.name"
							:placeholder="$t('equipment.programNameInput')"
							clearable
							size="small"
							@keyup.enter.native="handleQuery"
						/>
					</el-form-item>
					<el-form-item :label="$t('program.style')" prop="type">
						<el-select
							v-model="queryParams.type"
							:placeholder="$t('program.styleInput')"
							clearable
							size="small"
							@change="handleTypeChange"
						>
							<el-option :label="$t('program.style1')" value="0" />
							<!-- <el-option label="LED节目" value="1" /> -->
							<el-option :label="$t('program.style2')" value="2" />
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('program.status')" prop="status">
						<el-select
							v-model="queryParams.status"
							:placeholder="$t('program.statusInput')"
							clearable
							size="small"
						>
							<el-option
								v-for="dict in statusOptions"
								:key="dict.value"
								:label="dict.label"
								:value="dict.value"
							/>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('elButton.establishTime')">
						<el-date-picker
							v-model="dateRange"
							size="small"
							style="width: 240px"
							value-format="yyyy-MM-dd"
							type="daterange"
							range-separator="-"
							:start-placeholder="$t('elButton.startTime')"
							:end-placeholder="$t('elButton.endTime')"
						/>
					</el-form-item>
					<el-form-item>
						<el-button
							type="primary"
							icon="el-icon-search"
							size="mini"
							@click="handleQuery"
							>{{ $t('elButton.search') }}</el-button
						>
						<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
							$t('elButton.reset')
						}}</el-button>
					</el-form-item>
				</el-form>

				<el-row :gutter="10" class="mb8">
					<el-col :span="1.5">
						<el-button
							v-hasPerm="['program_add']"
							type="primary"
							icon="el-icon-plus"
							size="mini"
							@click="handleAdd"
							>{{ $t('elButton.add') }}
						</el-button>
					</el-col>
					<!--<el-col :span="1.5">
            <el-button
              v-hasPerm="['program_edit']"
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleEdit"
            >修改
            </el-button>
          </el-col>-->
					<el-col :span="1.5">
						<el-button
							v-hasPerm="['program_del']"
							type="danger"
							icon="el-icon-delete"
							size="mini"
							:disabled="multiple"
							@click="handleDel"
							>{{ $t('elButton.delete') }}
						</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button
							v-hasPerm="['program_edit']"
							type="success"
							icon="el-icon-position"
							size="mini"
							:disabled="multiple"
							@click="handleMoveTo"
							>{{ $t('programUntils') }}
						</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button
							v-hasPerm="['program_export']"
							type="warning"
							icon="el-icon-download"
							size="mini"
							:disabled="single"
							@click="handleExport"
							>{{ $t('elButton.export') }}
						</el-button>
						<el-button
							type="warning"
							icon="el-icon-upload2"
							size="mini"
							@click="handleImport"
							>{{ '导入' }}
						</el-button>
					</el-col>
					<div class="top-right-btn">
						<el-tooltip
							class="item"
							effect="dark"
							:content="$t('elButton.refresh')"
							placement="top"
						>
							<el-button
								size="mini"
								circle
								icon="el-icon-refresh"
								@click="handleQuery"
							/>
						</el-tooltip>
						<el-tooltip
							class="item"
							effect="dark"
							:content="
								showSearch
									? $t('elButton.hideSearch')
									: $t('elButton.showSearch')
							"
							placement="top"
						>
							<el-button
								size="mini"
								circle
								icon="el-icon-search"
								@click="showSearch = !showSearch"
							/>
						</el-tooltip>
					</div>
				</el-row>

				<el-table
					v-loading="loading"
					:data="programList"
					@selection-change="handleSelectionChange"
				>
					<el-table-column type="selection" width="55" align="center" />
					<el-table-column
						:label="$t('program.number')"
						align="center"
						width="60"
						prop="id"
					/>
					<el-table-column
						:label="$t('equipment.programName')"
						align="center"
						prop="name"
						:show-overflow-tooltip="true"
					/>
					<el-table-column
						:label="$t('program.programStyle')"
						align="center"
						prop="type"
					>
						<template slot-scope="scope">
							<el-tag v-if="scope.row.type == '0'">
								{{ $t('program.style1') }}
							</el-tag>
							<!-- <el-tag v-if="scope.row.type == '1'" type="info">LED节目</el-tag> -->
							<el-tag v-if="scope.row.type == '2'" type="warning">{{
								$t('program.style2')
							}}</el-tag>
						</template>
					</el-table-column>
					<el-table-column
						:label="$t('equipment.sort')"
						align="center"
						prop="groupName"
					/>
					<el-table-column
						:label="$t('equipment.resolving')"
						align="center"
						prop="width"
					>
						<template slot-scope="scope">
							<span v-if="scope.row.width != null"
								>{{ scope.row.width }}*{{ scope.row.height }}</span
							>
							<span v-else>{{ $t('notYet') }}</span>
						</template>
					</el-table-column>
					<el-table-column
						:label="$t('program.sceneNumber')"
						align="center"
						prop="scene"
					/>
					<el-table-column
						:label="$t('program.totalTime')"
						align="center"
						prop="duration"
					/>
					<el-table-column
						:label="$t('program.status')"
						align="center"
						prop="status"
						:formatter="statusFormat"
					/>
					<el-table-column
						:label="$t('equipment.createTime')"
						align="center"
						prop="createTime"
						width="180"
					>
						<template slot-scope="scope">
							<span>{{ parseTime(scope.row.createTime) }}</span>
						</template>
					</el-table-column>
					<el-table-column
						width="240px"
						:label="$t('equipment.control')"
						align="center"
						class-name="small-padding fixed-width"
						fixed="right"
					>
						<template slot-scope="scope">
							<el-button
								v-if="scope.row.status == '0' || scope.row.status == '3'"
								v-hasPerm="['program_audit']"
								size="mini"
								type="text"
								icon="el-icon-circle-check"
								@click="handleAudit(scope.row)"
								>{{ $t('elButton.examine') }}
							</el-button>
							<el-button
								v-if="scope.row.status != '0'"
								v-hasPerm="['program_audit']"
								size="mini"
								type="text"
								icon="el-icon-tickets"
								@click="auditRecord(scope.row)"
								>{{ $t('elButton.examineRecord') }}
							</el-button>
							<el-button
								v-if="scope.row.type == '0'"
								v-hasPerm="['program_edit']"
								size="mini"
								type="text"
								icon="el-icon-view"
								@click="handlePreview(scope.row)"
								>{{ $t('elButton.preview') }}
							</el-button>
							<el-button
								v-hasPerm="['program_edit']"
								size="mini"
								type="text"
								icon="el-icon-edit"
								@click="handleEdit(scope.row)"
								>{{ $t('elButton.change') }}
							</el-button>
							<el-button
								v-hasPerm="['program_copy']"
								size="mini"
								type="text"
								icon="el-icon-tickets"
								@click="handleCopy(scope.row)"
								>{{ $t('elButton.copy') }}
							</el-button>
							<el-button
								v-hasPerm="['program_del']"
								size="mini"
								type="text"
								icon="el-icon-delete"
								@click="handleDel(scope.row)"
								>{{ $t('elButton.delete') }}
							</el-button>
						</template>
					</el-table-column>
				</el-table>

				<pagination
					v-show="total > 0"
					:total="total"
					:page.sync="queryParams.current"
					:limit.sync="queryParams.size"
					@pagination="getList"
				/>
			</el-col>
		</el-row>

		<!-- 审核记录 -->
		<el-dialog
			:title="title"
			:visible.sync="auditRecordOpen"
			:modal-append-to-body="true"
			:append-to-body="true"
		>
			<el-table v-loading="loading" :data="auditRecordList" max-height="70vh">
				<el-table-column
					:label="$t('program.reviewer')"
					align="center"
					prop="checkBy"
				/>
				<el-table-column
					:label="$t('program.auditStatus')"
					align="center"
					prop="status"
				>
					<template slot-scope="scope">
						<span v-if="scope.row.status === 2">{{
							$t('program.auditStatus1')
						}}</span>
						<span v-if="scope.row.status === 3">{{
							$t('program.auditStatus2')
						}}</span>
					</template>
				</el-table-column>
				<el-table-column
					:label="$t('equipment.remarks')"
					align="center"
					prop="remarks"
				/>
				<el-table-column
					:label="$t('wel.info.time')"
					align="center"
					prop="checkTime"
					width="180"
				>
					<template slot-scope="scope">
						<span>{{ parseTime(scope.row.checkTime) }}</span>
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>

		<!-- 添加或修改节目对话框 -->
		<el-dialog
			class="custom-dialog"
			:title="title"
			:visible.sync="open"
			:modal-append-to-body="true"
			:append-to-body="true"
			:close-on-click-modal="false"
			@closed="handleClosed"
		>
			<el-form ref="form" :model="form" :rules="rules" label-width="100px">
				<el-row>
					<el-col :span="24">
						<el-form-item :label="$t('program.programStyle')" prop="type">
							<el-radio-group
								v-model="form.type"
								size="medium"
								:disabled="form.id"
								@change="handleTypeChange"
							>
								<el-radio border label="0">{{ $t('program.style1') }}</el-radio>
								<!-- <el-radio border label="1">LED节目</el-radio> -->
								<el-radio border label="2">{{ $t('program.style2') }}</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item :label="$t('equipment.programName')" prop="name">
							<el-input
								v-model="form.name"
								:placeholder="$t('equipment.programNameInput')"
							/>
						</el-form-item>
					</el-col>
					<!--分组-->
					<el-col :span="24">
						<el-form-item :label="$t('equipment.sort')" prop="groupId">
							<treeselect
								@input="inputSelect"
								v-model="form.groupId"
								:options="groupOptions.length ? groupOptions[0].children : []"
								:normalizer="normalizer"
								:placeholder="$t('equipment.sortInput')"
							/>
						</el-form-item>
					</el-col>
					<el-col v-if="form.type == 0" :span="24">
						<el-form-item :label="$t('equipment.resolving')" prop="resolution">
							<el-select
								v-model="form.resolution"
								:placeholder="$t('equipment.resolvingInput')"
								@change="handleResolutionChange"
							>
								<el-option
									v-for="it in resolutionList"
									:key="it"
									:label="it"
									:value="it"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col v-if="showCustomResolution" :span="12">
						<el-form-item :label="$t('program.width')" prop="customWidth">
							<el-input
								v-model="form.customWidth"
								type="number"
								:placeholder="$t('program.widthInput')"
							/>
						</el-form-item>
					</el-col>
					<el-col v-if="showCustomResolution" :span="12">
						<el-form-item :label="$t('program.height')" prop="customWidth">
							<el-input
								v-model="form.customHeight"
								type="number"
								:placeholder="$t('program.heightInput')"
							/>
						</el-form-item>
					</el-col>
					<el-col v-if="form.type == 1" :span="12">
						<el-form-item :label="$t('program.rollingSpeed')" prop="speed">
							<el-select
								v-model="layout.speed"
								:placeholder="$t('program.rollingSpeedInput')"
							>
								<el-option :label="$t('program.rollingSpeed1')" value="0" />
								<el-option :label="$t('program.rollingSpeed2')" value="1" />
								<el-option :label="$t('program.rollingSpeed3')" value="2" />
								<el-option :label="$t('program.rollingSpeed4')" value="3" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col v-if="form.type == 1" :span="12">
						<el-form-item :label="$t('program.stuntStyle')" prop="displayStyle">
							<el-select
								v-model="layout.displayStyle"
								:placeholder="$t('program.stuntStyleInput')"
							>
								<el-option :label="$t('program.stuntStyle1')" value="0" />
								<el-option :label="$t('program.stuntStyle2')" value="1" />
								<el-option :label="$t('program.stuntStyle3')" value="3" />
								<el-option :label="$t('program.stuntStyle4')" value="5" />
								<el-option :label="$t('program.stuntStyle5')" value="37" />
								<el-option :label="$t('program.stuntStyle6')" value="39" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col v-if="form.type == 1" :span="12">
						<el-form-item :label="$t('program.font')" prop="fontFamily">
							<el-select
								v-model="layout.fontFamily"
								:placeholder="$t('program.fontInput')"
							>
								<el-option :label="$t('program.font1')" value="宋体" />
								<el-option :label="$t('program.font2')" value="黑体" />
								<el-option :label="$t('program.font3')" value="微软雅黑" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col v-if="form.type == 1" :span="12">
						<el-form-item :label="$t('program.fontWeight')" prop="bold">
							<el-radio-group v-model="layout.bold" size="medium">
								<el-radio border label="0">{{ $t('yes') }}</el-radio>
								<el-radio border label="1">{{ $t('no') }}</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col v-if="form.type == 1" :span="12">
						<el-form-item :label="$t('program.fontSize')" prop="fontSize">
							<el-select
								v-model="layout.fontSize"
								:placeholder="$t('program.fontSizeInput')"
							>
								<el-option label="16" value="16" />
								<el-option label="20" value="20" />
								<el-option label="24" value="24" />
								<el-option label="28" value="28" />
								<el-option label="32" value="32" />
								<el-option label="36" value="36" />
								<el-option label="40" value="40" />
								<el-option label="60" value="60" />
								<el-option label="80" value="80" />
								<el-option label="100" value="100" />
								<el-option label="150" value="150" />
								<el-option label="200" value="200" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col v-if="form.type == 1" :span="24">
						<el-form-item :label="$t('program.programContent')" prop="content">
							<el-input
								v-model="layout.content"
								type="textarea"
								rows="3"
								:placeholder="$t('program.programContentInput')"
							/>
						</el-form-item>
					</el-col>
					<el-col v-if="form.type == 2" :span="24">
						<el-form-item prop="layout">
							<span slot="label">
								{{ $t('program.programTemplate') }}
								<el-tooltip
									:content="$t('program.programTemplateInput')"
									placement="top"
								>
									<i class="el-icon-question" />
								</el-tooltip>
							</span>
							<el-upload
								ref="upload"
								drag
								accept=".zip"
								:show-file-list="false"
								:headers="{ Authorization: 'Bearer ' + getAccessToken() }"
								:action="uploadUrl()"
								:on-success="handleOnSuccess"
								:on-error="handleOnError"
							>
								<i class="el-icon-upload" />
								<div class="el-upload__text">
									{{ $t('edition.uploadDrop')
									}}<em>{{ $t('edition.uploadClick') }}</em>
								</div>
							</el-upload>
							<p v-if="form.type == 2 && form.layout">{{ form.layout }}</p>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">{{
					$t('submitText')
				}}</el-button>
				<el-button @click="cancel">{{ $t('cancelText') }}</el-button>
			</div>
		</el-dialog>

		<!-- 移至对话框 -->
		<el-dialog
			:title="$t('program.moveSort')"
			:visible.sync="mtOpen"
			width="560px"
			center
			:modal-append-to-body="true"
			:append-to-body="true"
		>
			<el-form label-width="85px">
				<el-row>
					<el-col :span="24">
						<el-form-item :label="$t('equipment.sort')">
							<treeselect
								v-model="groupId"
								:options="groupOptions.length ? groupOptions[0].children : []"
								:normalizer="normalizer"
								:placeholder="$t('equipment.sortInput')"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="small" @click="mtCancel">{{
					$t('cancelText')
				}}</el-button>
				<el-button size="small" type="primary" @click="mtSubmitForm">{{
					$t('submitText')
				}}</el-button>
			</div>
		</el-dialog>

		<!--添加/编辑分组-->
		<el-dialog
			:visible.sync="groupDialogVisible"
			:title="$t('equipment.sortTitle')"
			width="30%"
			class="wrapper"
			:modal-append-to-body="true"
			:append-to-body="true"
			@closed="groupDialogClosed"
		>
			<el-form
				ref="form"
				:model="groupObj"
				@submit.native.prevent
				:rules="groupRules"
				label-width="80px"
			>
				<el-form-item :label="$t('equipment.sort')" prop="name">
					<el-input
						ref="name"
						v-model="groupObj.name"
						size="small"
						@keyup.enter.native="handleClickSaveGroup"
					/>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="handleClickSaveGroup">{{
					$t('submitText')
				}}</el-button>
				<el-button @click="groupDialogVisible = false">{{
					$t('cancelText')
				}}</el-button>
			</span>
		</el-dialog>

		<!-- 导入节目  -->
		<el-dialog
			:visible.sync="importProgramDialogVisible"
			title="导入节目"
			width="30%"
			class="wrapper"
			:modal-append-to-body="true"
			:append-to-body="true"
		>
			<el-form
				ref="form"
				label-width="100px"
				:rules="rules"
				@submit.native.prevent
				:model="importProgramData"
			>
				<el-form-item label="节目类型" prop="type">
					<el-radio-group v-model="importProgramData.type">
						<el-radio :label="0">普通节目</el-radio>
						<el-radio :label="1">自定义节目</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="节目名称" prop="name">
					<el-input v-model="importProgramData.name"></el-input>
				</el-form-item>
				<el-form-item label="分组名称" prop="groupName">
					<el-select v-model="importProgramData.groupName">
						<el-option
							v-for="item in groupOptions[0].children"
							:key="item.id"
							:label="item.name"
							:value="item.id"
						>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="上传节目包" prop="file">
					<!-- <input  ref="uploadFile"  type="file" @change="uploadProgram"></input> -->
					<el-upload
						ref="uploadFile"
						action="https://jsonplaceholder.typicode.com/posts/"
						:on-change="uploadProgram"
						:on-remove="handleRemove"
						:limit="1"
						:file-list="importProgramData.file"
						:auto-upload="false"
					>
						<el-button size="small" type="primary">点击上传</el-button>
					</el-upload>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="importProgramDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="importProgram">确 定</el-button>
			</span>
		</el-dialog>

		<!--审核页面-->
		<audit
			:obj="auditObj"
			:audit-title="$t('program.programshenhe')"
			:visible.sync="auditVisible"
			audit-type="program"
			@refresh="getList"
		/>
	</div>
</template>

<script>
import {
	listProgram,
	delProgram,
	addProgram,
	editProgram,
	moveTo,
	exportProgram,
	importProgram,
	copyProgram,
} from '@/api/ips/program'
import { saveAs } from 'file-saver'
import JsZip from 'jszip'
import { addGroup, delGroup, editGroup, groupTree } from '@/api/ips/group'
import { listauditRecord } from '@/api/ips/audit'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getLabelByValInTree } from '@/utils/obj-util'
import AuditMixin from '@/mixins/audit/index.js'
import { setKV } from '@/utils/storage-util'
import { getAccessToken } from '@/data/user'
import { isEmpty } from 'ramda'
export default {
	name: 'Program',
	components: { Treeselect },
	mixins: [AuditMixin],
	data() {
		const nameValidator = (rule, val, callback) => {
			if (val) {
				callback()
			} else {
				callback(new Error(this.$t('equipment.groupingInput')))
			}
		}
		const customWidthValidator = (rule, val, callback) => {
			if (this.showCustomResolution) {
				if (val) {
					callback()
				} else {
					callback(new Error(this.$t('program.widthInput')))
				}
			} else {
				callback()
			}
		}
		const customHeightValidator = (rule, val, callback) => {
			if (this.showCustomResolution) {
				if (val) {
					callback()
				} else {
					callback(new Error(this.$t('program.heightInput')))
				}
			} else {
				callback()
			}
		}
		const layoutContentValidator = (rule, val, callback) => {
			if (this.showLayout) {
				if (this.layout.content) {
					callback()
				} else {
					callback(new Error(this.$t('program.programContentInput')))
				}
			} else {
				callback()
			}
		}
		return {
			name: '',
			getAccessToken,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 总条数
			total: 0,
			// 节目表格数据
			programList: [],
			// 弹出层标题
			title: '',
			// 是否显示弹出层
			open: false,
			mtOpen: false,
			groupId: undefined,
			groupName: undefined,
			// 日期范围
			dateRange: [],
			statusOptions: [], // 查询参数
			name: undefined,
			groupOptions: [
				{children: []} // 控制台报错
			],
			groupDict: [],
			layout: {
				speed: '0',
				displayStyle: '0',
				fontFamily: '黑体',
				bold: '1',
				fontSize: '16',
				fonetColor: '#ED4014',
				bgColor: '#000000',
			},
			defaultProps: {
				children: 'children',
				label: 'name',
			},
			queryParams: {
				current: 1,
				size: 10,
				fullPathId: 40,
				name: undefined,
				type: undefined,
				isTemplate: '0',
				status: undefined,
				createTime: undefined,
			},
			// 显示搜索条件
			showSearch: true,
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				type: [
					{
						required: true,
						message: this.$t('program.programStyleEmpty'),
						trigger: 'blur',
					},
				],
				name: [
					{
						required: true,
						message: this.$t('equipment.programNameEmpty'),
						trigger: 'blur',
					},
				],
				groupId: [
					{
						required: true,
						message: this.$t('equipment.sortEmpty'),
						trigger: 'change',
					},
				],
				groupName: [
					{
						required: true,
						message: this.$t('equipment.programNameEmpty'),
						trigger: 'change',
					},
				],
				uploadFile: [
					{
						required: true,
						message: this.$t('equipment.programNameEmpty'),
						trigger: 'change',
					},
				],
				customWidth: [{ validator: customWidthValidator }],
				customHeight: [{ validator: customHeightValidator }],
				content: [{ validator: layoutContentValidator }],
			},
			VUE_APP_BASE_API: process.env.VUE_APP_BASE_API,
			// 分组相关
			groupDialogVisible: false,
			groupObj: { name: undefined },
			groupRules: {
				name: [{ validator: nameValidator }],
			},
			importRules: {
				name: [{ validator: nameValidator }],
			},
			// 分辨率
			resolutionList: [
				'1920*1080',
				'1080*1920',
				'1366*768',
				'1280*720',
				'720*1280',
				'自定义',
			],
			// 审核记录
			auditRecordOpen: false,
			auditRecordList: [],
			// 是否显示自定义分辨率输入框
			showCustomResolution: false,
			showLayout: false,
			importProgramDialogVisible: false,
			importProgramData: {}, // 导入的节目数据
		}
	},
	watch: {
		// 根据名称筛选分组名称树
		name(val) {
			this.$refs.tree.filter(val)
		},
	},
	created() {
		// 判断是否有存储的页面
		if (!isEmpty(this.$route.params)) {
			this.queryParams = this.$route.params
		}
		if (this.$route.query.name) {
			this.queryParams.name = this.$route.query.name
		}
		this.getList()
		this.getGroupTree()
		this.getDicts('check_status').then((response) => {
			this.statusOptions = response.data
		})
		if (this.$route.query.handleAdd) {
			this.handleAdd()
		}
	},

	methods: {
		// 导入节目
		async importProgram() {
			let formdata = new FormData()
			formdata.append('zipFile', this.importProgramData.file)
			await importProgram(
				this.importProgramData.groupName,
				this.importProgramData.name,
				formdata
			)
			this.importProgramDialogVisible = false
			this.getList()
			this.getGroupTree()
		},
		handleRemove(file) {
			this.importProgramData.file = undefined
		},
		// 上传节目文件
		uploadProgram(file, fileList) {
			this.importProgramData.file = file.raw
		},
		inputSelect() {
			this.$refs.form.validateField('groupId')
		},
		// 点击了模板
		handleClickEdit(it) {},
		/** 查询节目列表 */
		getList() {
			this.loading = true
			listProgram(this.addDateRange(this.queryParams, this.dateRange)).then(
				(response) => {
					this.programList = response.data
					this.total = response.total
					this.loading = false
				}
			)
		},
		/** 转换机构数据结构 */
		normalizer(node) {
			if (node.children && !node.children.length) {
				delete node.children
			}
			return {
				id: node.id,
				label: node.name,
				children: node.children,
			}
		},
		/** 查询分组名称下拉树结构 */
		getGroupTree() {
			groupTree({ groupId: 40 }).then((response) => {
				this.groupOptions = response.data
				console.log(`<<<<2023年03月24日 11:08:52>>>>`, {
					'this.groupOptions': this.groupOptions,
				})
				this.groupDict = []
				const findChildren = (arr, list) => {
					for (let i = 0; i < arr.length; i++) {
						if (arr[i].id) {
							list.push(arr[i])
						}
						if (arr[i].children && arr[i].children.length) {
							findChildren(arr[i].children, list)
						}
					}
				}
				findChildren(this.groupOptions, this.groupDict)
			})
		},
		// 筛选节点
		filterNode(value, data) {
			if (!value) return true
			return data.name.indexOf(value) !== -1
		},
		// 节点单击事件
		handleNodeClick(data) {
			this.queryParams.fullPathId = data.id
			this.queryParams.current = 1
			this.getList()
		},
		// 状态字典翻译
		statusFormat(row, column) {
			return this.selectDictLabel(this.statusOptions, row.status)
		},
		// 取消按钮
		cancel() {
			this.open = false
			this.reset()
		},
		// 表单重置
		reset() {
			const d = new Date()
			const year = d.getFullYear()
			const month =
				d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
			const date = d.getDate() < 10 ? '0' + d.getDate() : d.getDate()
			const hour = d.getHours() < 10 ? '0' + d.getHours() : d.getHours()
			const minute = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()
			const second = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds()
			const times = year + '' + month + date + hour + minute + second
			this.form = {
				id: undefined,
				resolution: '1920*1080',
				customWidth: undefined,
				customHeight: undefined,
				name: '节目-' + times + (Math.floor(Math.random() * (99 - 10)) + 10),
				groupId: undefined,
				groupName: undefined,
				cover: undefined,
				type: '0',
				width: undefined,
				height: undefined,
				duration: undefined,
				layout: undefined,
				isTemplate: '0',
				deptId: undefined,
				status: undefined,
			}
			this.resetForm('form')
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.current = 1
			// this.queryParams.name = ''
			// this.$route.query.name = ''
			this.getList()
		},
		handleQueryAll() {
			this.queryParams.fullPathId = ''
			this.getList()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.dateRange = []
			this.resetForm('queryForm')
			this.handleQuery()
			const path = this.$route.path // 先获取路由路径
			this.$router.push(path)
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map((item) => item.id)
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset()
			this.open = true
			this.title = '添加节目'
		},
		// 上传的url
		uploadUrl() {
			return `${this.VUE_APP_BASE_API}/ips/program/upload`
		},
		handleOnSuccess(res) {
			console.log(JSON.stringify(res))
			if (res.code === 0) {
				this.form.layout = res.data
			}
		},
		// 上传失败
		handleOnError() {
			this.$message({
				message: this.$t('edition.uploadFail'),
				type: 'error',
				showClose: true,
			})
		},
		// 点击预览按钮
		handlePreview(row) {
			const programData = JSON.parse(row.layout)
			programData.sacle = 1.0
			this.$EventBus.$emit('PREVIEW', programData)
		},
		/** 修改按钮操作 */
		handleEdit(row) {
			this.reset()
			this.form = JSON.parse(JSON.stringify(row))
			this.form.isCopy = '0'
			if (this.form.type === '0') {
				setKV('PREVIOUS_ROUTE', 'program')
				setKV('PROGRAM_INFO', JSON.stringify(this.form))
				// 携带当前节目信息
				this.queryParams.program = row
				setTimeout(() => {
					this.$router.push({ name: 'editor', params: this.queryParams })
				}, 50)
			} else if (this.form.type === '1') {
				this.layout = JSON.parse(this.form.layout)
				this.open = true
				/* getProgram(this.form.id).then(response => {
            if (response.code === 0) {
              this.open = true
              this.layout = JSON.parse(this.form.layout);
            } else {
              this.msgError(response.msg)
            }
          })*/
			} else {
				this.form.resolution = this.form.width + '*' + this.form.height
				this.open = true
			}
		},
		/** 复制按钮操作 */
		handleCopy(row) {
			this.reset()
			this.form = JSON.parse(JSON.stringify(row))
			this.form.isCopy = '1'
			if (this.form.type === '0') {
				setKV('PREVIOUS_ROUTE', 'program')
				setKV('PROGRAM_INFO', JSON.stringify(this.form))
				// 携带当前节目信息
				this.queryParams.program = row
				setTimeout(() => {
					this.$router.push({ name: 'editor', params: this.queryParams })
				}, 50)
			} else if (this.form.type === '1') {
				this.layout = JSON.parse(this.form.layout)
				this.open = true
				/* getProgram(this.form.id).then(response => {
            if (response.code === 0) {
              this.open = true
              this.layout = JSON.parse(this.form.layout);
            } else {
              this.msgError(response.msg)
            }
          })*/
			} else {
				this.form.resolution = this.form.width + '*' + this.form.height
				this.open = true
			}
		},
		/** 提交按钮 */
		submitForm() {
			if (Number(this.form.customWidth) > 3840) {
				this.msgWarning('宽度不能超过3840')
				return
			}
			if (Number(this.form.customHeight) > 2160) {
				this.msgWarning('高度不能超过2160')
				return
			}
			this.$refs['form'].validate((valid) => {
				if (valid) {
					this.form.groupName = getLabelByValInTree(
						this.groupDict,
						this.form.groupId,
						{
							label: 'name',
							value: 'id',
						}
					)
					if (this.form.type === '0') {
						setKV('PREVIOUS_ROUTE', 'program')
						setKV('PROGRAM_INFO', JSON.stringify(this.form))
						// 携带当前节目信息
						this.form.id = ''
						this.queryParams.program = JSON.parse(JSON.stringify(this.form))
						setTimeout(() => {
							this.$router.push({ name: 'editor', params: this.queryParams })
						}, 50)
						// this.$router.push('/editor')
					} else {
						if (this.form.type === '1') {
							this.form.layout = JSON.stringify(this.layout)
						} else {
							this.form.scene = 1
							const ss = this.form.resolution.split('*')
							this.form.width = ss[0]
							this.form.height = ss[1]
						}
						if (this.form.id !== undefined && this.form.isCopy === '1') {
							this.form.id = undefined
							copyProgram(this.form).then((response) => {
								if (response.code === 0) {
									this.msgSuccess('复制成功')
									this.open = false
									this.getList()
								} else {
									this.msgError(response.msg)
								}
							})
						} else if (this.form.id !== undefined) {
							editProgram(this.form).then((response) => {
								if (response.code === 0) {
									this.msgSuccess(this.$t('loginLog.changeSuccess'))
									this.open = false
									this.getList()
								} else {
									this.msgError(response.msg)
								}
							})
						} else {
							addProgram(this.form).then((response) => {
								if (response.code === 0) {
									this.msgSuccess(this.$t('addSuccess'))
									this.open = false
									this.getList()
								} else {
									this.msgError(response.msg)
								}
							})
						}
					}
				}
			})
		},
		/** 删除按钮操作 */
		handleDel(row) {
			const ids = row.id || this.ids
			this.$confirm(
				this.$t('program.programNumberDelete') +
					ids +
					this.$t('equipment.deleteEquipment2'),
				this.$t('warning'),
				{
					confirmButtonText: this.$t('submitText'),
					cancelButtonText: this.$t('cancelText'),
					type: 'warning',
				}
			)
				.then(function() {
					return delProgram(ids)
				})
				.then(() => {
					this.getList()
					this.msgSuccess(this.$t('deleteSuccess'))
				})
				.catch(function() {})
		},
		handleMoveTo(row) {
			const ids = row.id || this.ids
			if (!ids) {
				this.msgWarning(this.$t('material.materialSortSelect'))
				return
			}
			this.groupId = undefined
			this.groupName = undefined
			this.mtOpen = true
		},
		mtCancel() {
			this.mtOpen = false
		},
		mtSubmitForm(row) {
			const ids = row.id || this.ids
			if (!this.groupId) {
				this.msgWarning(this.$t('material.materialSortInput'))
				return
			}
			this.groupName = getLabelByValInTree(this.groupOptions, this.groupId, {
				label: 'name',
				value: 'id',
			})
			moveTo(ids, this.groupId, this.groupName).then((response) => {
				if (response.code === 0) {
					this.msgSuccess(this.$t('operationSuccess'))
					this.mtOpen = false
					this.getList()
				} else {
					this.msgError(response.msg)
				}
			})
		},
		auditRecord(row) {
			const type = 'program'
			listauditRecord(type, row.id).then((response) => {
				this.title = this.$t('elButton.examineRecord')
				this.auditRecordList = response.data
				this.auditRecordOpen = true
			})
		},
		/** 导出按钮操作 */
		handleExport(row) {
			const ids = row.id || this.ids
			if (ids.length === 0) {
				this.msgWarning('请选择节目')
				return
			}
			const queryParams = this.queryParams
			this.$confirm(
				this.$t('program.exportAllProgramData'),
				this.$t('warning'),
				{
					confirmButtonText: this.$t('submitText'),
					cancelButtonText: this.$t('cancelText'),
					type: 'warning',
				}
			).then(async (result) => {
				const { data } = await exportProgram(queryParams, ids[0])
				const link = document.createElement('a') // 创建a标签
				link.href = 'http://' + window.location.host + '/pro' + data
				link.click()
			})
		},
		/**
		 * 导入按钮操作
		 */
		handleImport(row) {
			this.importProgramData = {
				type: 0,
				name: undefined,
				groupName: undefined,
			}
			this.resetForm('form')
			if (this.$refs.uploadFile) {
				this.$refs.uploadFile.clearFiles()
			}
			this.importProgramDialogVisible = true
		},
		// 添加分组
		addGroup(node, data) {
			this.groupObj = {
				name: undefined,
				type: 'program',
				parentId: data.id,
			}
			this.groupDialogVisible = true
		},
		// 编辑分组
		editGroup(node, data) {
			this.groupObj = JSON.parse(JSON.stringify(data))
			this.groupDialogVisible = true
		},
		// 删除分组
		deleteGroup(node, data) {
			this.$confirm(
				this.$t('material.deleteMaterialSort') + data.name + '?',
				this.$t('warning'),
				{
					confirmButtonText: this.$t('submitText'),
					cancelButtonText: this.$t('cancelText'),
					type: 'warning',
				}
			)
				.then(function() {
					return delGroup(data.id)
				})
				.then(() => {
					this.getGroupTree()
					this.getList()
					this.msgSuccess(this.$t('deleteSuccess'))
				})
				.catch(function() {})
		},
		groupDialogClosed() {
			this.groupObj = { name: undefined }
		},
		handleClickSaveGroup(name = '') {
			if (name) {
				this.saveGroupTree()
			} else {
				this.$refs['form'].validate((valid) => {
					if (valid) {
						this.saveGroupTree()
					}
				})
			}
		},
		saveGroupTree() {
			const fun = this.groupObj.id ? editGroup : addGroup
			fun(this.groupObj)
				.then((_) => {
					this.getGroupTree()
					this.$message({
						message: this.$t('saveSuccess'),
						type: 'success',
						showClose: true,
					})
					this.groupDialogVisible = false
				})
				.catch((_) => {})
		},
		handleResolutionChange(val) {
			this.showCustomResolution = val === '自定义'
		},
		handleClosed() {
			this.showCustomResolution = false
			this.showLayout = false
		},
		handleTypeChange(val) {
			this.showLayout = val !== '0'
			console.log(this.showLayout)
		},
	},
}
</script>

<style lang="scss" scoped>
.tree {
	overflow-x: auto;
}
.el-tree {
	min-width: 100%;
	display: inline-block;
}
.app-container {
	.custom-tree-item {
		&:after {
			content: '';
			display: block;
			clear: both;
		}

		&:hover {
			.right-btns {
				opacity: 1;
			}
		}

		font-size: 16px;
		width: 100%;

		.right-btns {
			float: right;
			color: #000;
			opacity: 0;
			transition: 0.3s all;
			user-select: none;

			.svg-icon {
				margin: 0 2px;

				&:hover {
					color: #999;
				}
			}
		}
	}

	.custom-dialog {
		.el-select {
			width: 100%;
		}
	}
}
</style>
